#!/usr/bin/python3
# -*- coding: utf-8 -*-

"""
# @version: v1.0
# @author : wlisingle
# @Email : 19688513@qq.com
# @Project : g-carbon-bio
# @File : stock_bidask_fetcher.py
# @Software: PyCharm
# @time: 2025/2/17 20:18
# @description : 
"""

import time
import akshare as ak
import pandas as pd

class StockBidAskFetcher:
    def __init__(self):
        pass  # 可以在此处初始化任何需要的属性

    @staticmethod
    def get_stock_data(code: str):
        """
        获取指定股票的外盘和内盘数据。

        :param code: 股票代码
        :return: 外盘和内盘的数值 (outer_disk, inner_disk)
        """
        # 添加延迟时间，避免频繁请求
        time.sleep(0.1)

        # 设置重试次数和计数器
        max_retries = 3
        retry_count = 0
        stock_bid_ask_em_df = None  # 初始化 DataFrame

        while retry_count < max_retries:
            try:
                stock_bid_ask_em_df = ak.stock_bid_ask_em(symbol=code)
                print(f"成功获取数据: {code}")
                break  # 退出循环，因为成功获取数据
            except Exception as e:
                print(f"获取数据时出错: {e}")
                retry_count += 1
                if retry_count < max_retries:
                    print("尝试重新获取数据...")
                    time.sleep(1)  # 等待1秒后重试
                else:
                    print("已达到最大重试次数，无法获取数据")

        # 提取外盘和内盘，并确保转换为数字类型
        outer_disk = stock_bid_ask_em_df.loc[stock_bid_ask_em_df['item'] == '外盘', 'value'].values[
            0] if not stock_bid_ask_em_df.empty else None
        inner_disk = stock_bid_ask_em_df.loc[stock_bid_ask_em_df['item'] == '内盘', 'value'].values[
            0] if not stock_bid_ask_em_df.empty else None

        # 转换为浮点数（或整数，根据需要），并处理无效值
        outer_disk = StockBidAskFetcher.convert_to_float(outer_disk)
        inner_disk = StockBidAskFetcher.convert_to_float(inner_disk)

        return outer_disk, inner_disk

    @staticmethod
    def convert_to_float(value):
        """将字符串或其他类型的值转换为浮点数"""
        if isinstance(value, str) and value.strip() == '-':
            return None
        try:
            return float(value)
        except ValueError:
            print(f"无法将值转换为数字: {value}")
            return None


# 示例用法
# if __name__ == "__main__":
#     fetcher = StockBidAskFetcher()
#     outer, inner = fetcher.get_stock_data("600000")
#     print(f"外盘: {outer}, 内盘: {inner}")
